﻿//-----------------------------------------------------------------------------
// Copyright (c) BaFang Corporation.  All rights reserved.
//-----------------------------------------------------------------------------

namespace BaFangSpider
{
    using System.Collections.Generic;
    using System;
    using LumiSoft.Net.Mail;

    /// <summary>
    /// Summary description for QQOnlineService
    /// </summary>
    public class QQOnlineMonitorService : MonitorService
    {
        private string baseAddress = @"http://wpa.qq.com/pa?p=1:{0}:5";
        private Dictionary<string, ListenerManager> qqAndListeners = new Dictionary<string, ListenerManager>();
        private DataManager dataMan = new DataManager("qqLastStatus.xml", typeof(SerializableDictionary<string, bool>));
        private SerializableDictionary<string, bool> lastStatus;
        private static QQOnlineMonitorService instance = null;

        private QQOnlineMonitorService()
        {
            this.mailAddress = MailAccounts.GetInstance().QQ;
            lastStatus = dataMan.LoadData() as SerializableDictionary<string, bool>;
            if (lastStatus == null)
            {
                this.lastStatus = new SerializableDictionary<string, bool>();
            }
            foreach (string qq in this.lastStatus.Keys)
            {
                qqAndListeners.Add(qq, new ListenerManager(qq + ".xml", this.mailAddress));
            }
        }

        public static QQOnlineMonitorService GetInstance()
        {
            if (instance == null)
            {
                instance = new QQOnlineMonitorService();
            }
            return instance;
        }

        protected override void UpdateListenserRegisteredService(string interest, string message)
        {
            // remove originals
            // TODO: performance tuning.
            foreach (ListenerManager users in this.qqAndListeners.Values)
            {
                users.RemoveListener(interest);
            }

            if (!string.IsNullOrEmpty(message))
            {
                QQService service = ServiceBase.CreateFromString<QQService>(message) as QQService;
                foreach (QQServiceEntity entity in service.Entities)
                {
                    if (!qqAndListeners.ContainsKey(entity.Number))
                    {
                        qqAndListeners.Add(entity.Number, new ListenerManager(entity.Number+ ".xml", this.mailAddress));
                    }
                    // Add qq's listener.
                    ListenerManager listenManager = qqAndListeners[entity.Number];
                    listenManager.AddListener(interest, entity.NickName);

                    bool isOnline = IsQQOnline(entity.Number);
                    this.lastStatus[entity.Number] = isOnline;
                }
            }
            List<string> removeKeys = new List<string>();
            foreach (KeyValuePair<string, ListenerManager> pair in this.qqAndListeners)
            {
                if (pair.Value.Count == 0)
                {
                    removeKeys.Add(pair.Key);
                }
            }
            foreach (string key in removeKeys)
            {
                this.qqAndListeners.Remove(key);
                this.lastStatus.Remove(key);
            }
            dataMan.SaveData(this.lastStatus);
        }

        protected override void CheckWebSites()
        {
            try
            {
                lock (this.qqAndListeners)
                {
                    Logger.GetLogger().Write("begin Check qq online status and send mail, qq count is " 
                        + qqAndListeners.Count);
                    foreach (string qq in this.qqAndListeners.Keys)
                    {
                        bool current = this.IsQQOnline(qq);
                        bool last = false;
                        if (lastStatus.ContainsKey(qq))
                        {
                            last = lastStatus[qq];
                        }
                        lastStatus[qq] = current;
                        if (last == false && current == true)
                        {
                            Logger.GetLogger().Write("notify qq listener that the qq is online");
                            qqAndListeners[qq].NotifyListens(string.Format("您关心的qq<{0}><{1}> ,上线了！",
                                qq, qqAndListeners[qq].GetAdditional()), ConstStrings.UnregisterAlert);
                        }
                        if (last == true && current == false)
                        {
                            Logger.GetLogger().Write("notify qq listener that the qq is offline");
                            qqAndListeners[qq].NotifyListens(string.Format("您关心的qq<{0}><{1}>下线了！",
                                qq, qqAndListeners[qq].GetAdditional()), ConstStrings.UnregisterAlert);
                        }
                    }
                    dataMan.SaveData(this.lastStatus);
                }
            }
            catch
            { }
        }

        private bool IsQQOnline(string number)
        {
            string url = string.Format(baseAddress, number);
            int len = HtmlUtility.GetResponseLength(url);
            if (len < 1248)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}